package com.asen.commons.core.jdbc.handler;

import java.sql.*;

/**
 * Character 类型处理器
 *
 * @author Gary
 * @version 1.0
 * @date 2018-12-02
 */
public class CharacterTypeHandler extends BaseTypeHandler<Character> {

    @Override
    public int getSqlType() {
        return Types.VARCHAR;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Character parameter) throws SQLException {
        ps.setString(i, parameter.toString());
    }

    @Override
    public Character getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String columnValue = rs.getString(columnName);
        if (columnValue != null) {
            return columnValue.charAt(0);
        } else {
            return null;
        }
    }

    @Override
    public Character getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String columnValue = rs.getString(columnIndex);
        if (columnValue != null) {
            return columnValue.charAt(0);
        } else {
            return null;
        }
    }

    @Override
    public Character getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String columnValue = cs.getString(columnIndex);
        if (columnValue != null) {
            return columnValue.charAt(0);
        } else {
            return null;
        }
    }

    @Override
    public String toSqlValue(Object value) {
        if (value == null) {
            return null;
        }

        if (value instanceof char[]) {
            StringBuilder sb = new StringBuilder(0);
            sb.append("(");
            for (char s : (char[]) value) {
                if (sb.length() > 0) {
                    sb.append(", ");
                }
                sb.append("\'" + s + "\'");
            }
            sb.append(")");
            return sb.toString();
        }

        if (value instanceof Character[]) {
            StringBuilder sb = new StringBuilder(0);
            sb.append("(");
            for (Character s : (Character[]) value) {
                if (sb.length() > 0) {
                    sb.append(", ");
                }
                sb.append("\'" + s + "\'");
            }
            sb.append(")");
            return sb.toString();
        }

        return "\'" + String.valueOf(value) + "\'";
    }

    @Override
    public Character getValue(Object value) {
        if (value == null) {
            return null;
        }

        if (value instanceof Character) {
            return (Character) value;
        }

        char[] chars = value.toString().toCharArray();
        return chars.length > 0 ? Character.valueOf(chars[0]) : null;
    }
}
